const { app, BrowserWindow } = require('electron')
const path = require('path')
// 保持对window对象的全局引用，如果不这么做的话，当JavaScript对象被
// 垃圾回收的时候，window对象将会自动的关闭
const Application = {
  options: {},
  constructor: options => {
    Application.options = options
    return Application
  },
  run: () => {
    Application.appEventListener()
    Application.setSingleInstance()
  },
  createWindow: () => {
    // 创建浏览器窗口。
    global.electronWindow = new BrowserWindow({
      width: Application.options.width,
      height: Application.options.height,
      minWidth: Application.options.minWidth,
      minHeight: Application.options.minHeight,
      frame: Application.options.frame,
      show: Application.options.show,
      webPreferences: {
        contextIsolation: false,
        nodeIntegration: Application.options.nodeIntegration,
        preload: path.posix.join(__dirname, './renderer.js')
      }
    })
    // 加载index.html文件
    if(app.isPackaged){
      global.electronWindow.loadFile(path.posix.join(__dirname, './renderer/index.html'))
    }else{
      global.electronWindow.loadURL('http://localhost:8080')
      global.electronWindow.webContents.openDevTools()
    }
    Application.windowEventListener()
    require('./main/index')
  },
  windowEventListener: () => {
    global.electronWindow.on('ready-to-show', () => {
      global.electronWindow.show() // 初始化后再显示
    })
    // 当 window 被关闭，这个事件会被触发。
    global.electronWindow.on('closed', () => {
      global.electronWindow = null
    })
  },
  appEventListener: () => {
    app.on('ready', () => {
      Application.createWindow()
    })
    // 当全部窗口关闭时退出。
    app.on('window-all-closed', () => {
      if (process.platform !== 'darwin') {
        app.quit()
      }
    })
    app.on('activate', () => {
      if (global.electronWindow === null) {
        Application.createWindow()
      }
    })
  },
  setSingleInstance: () => {
    if (!app.requestSingleInstanceLock()) {
      app.quit()
    } else {
      app.on('second-instance', () => {
        if (global.electronWindow) {
          if (global.electronWindow.isMinimized()) global.electronWindow.restore()
          global.electronWindow.focus()
          global.electronWindow.show()
        }
      })
    }
  }
}
Application
  .constructor({
    height: 600,
    width: 800,
    minWidth: 500,
    minHeight: 300,
    frame: false,
    show: false,
    nodeIntegration: false
  })
  .run()
